package ru.compscicenter.databases.zaikina.common.model;

import org.json.simple.JSONArray;
import org.json.simple.JSONAware;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

public class NodeConfig implements JSONAware {
    private ArrayList<Node> nodes;
    private HashMap<Character, Integer> alphabet = new HashMap<Character, Integer>();

    public NodeConfig(ArrayList<Node> nodes) {
        this.nodes = nodes;
        int idx = 0;
        int num = 0;
        for (Node node : nodes) {
            if (node.getType() == NodeType.VocabularyNode) {
                char letter = (idx < 26) ? (char)('A' + idx) : (char)('А' + idx);
                alphabet.put(letter, num);
                ++idx;
            }
            ++num;
        }
    }

    public Node getNodeById(int id) {
        for (Node node : nodes) {
            if (node.getNodeId() == id) {
                return node;
            }
        }
        return null;
    }

    public Node getHttpServerNode() {
        return findByType(NodeType.HttpServer);
    }

    public Node getVocabularyNode(String word) {
        word = word.toUpperCase();
        if (word.length() == 0 || !alphabet.containsKey(word.charAt(0))) {
            return null;
        }

        int idx = alphabet.get(word.charAt(0));
        return nodes.get(idx);
    }

    public Node getFileStorageNode() {
         return findByType(NodeType.FileStorage);
    }

    private Node findByType(int type) {
        for (Node node : nodes) {
            if (node.getType() == type) {
                return node;
            }
        }
        return null;
    }


    public String toJSONString() {
       JSONObject jsonObject = new JSONObject();
       jsonObject.put("nodes", nodes);
       return jsonObject.toString();
    }

    public static NodeConfig parse(String jsonStr) {
        ArrayList<Node> nodes = new ArrayList<Node>();
        JSONObject nodesObj = (JSONObject) JSONValue.parse(jsonStr);
        JSONArray arr = (JSONArray) JSONValue.parse(nodesObj.get("nodes").toString());
        for (int i = 0; i < arr.size(); ++i) {
            Node node = Node.parse(arr.get(i).toString());
            if (node != null) {
                nodes.add(node);
            }
        }
        return new NodeConfig(nodes);
    }

    public static NodeConfig load() throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("../config.txt"));
        return parse(reader.readLine());
    }
}
